package com.dmall.tree;

import com.dmall.queue.LoopQueue;
import com.dmall.queue.Queue;

import java.util.Stack;

/**
 * 二分搜索树
 *
 * 二分搜索树不管是前序遍历、中序遍历还是后序遍历都是深度优先遍历
 *
 * @author xiao1.wang@dmall.com
 * @date 2019-03-24 17:40:30
 */
public class BinarySearchTree<E extends Comparable<E>> {

    private class Node {
        public E e;
        public Node left, right;

        public Node(E e) {
            this.e = e;
            this.left = null;
            this.right = null;
        }
    }

    private Node root;
    private int size;

    public BinarySearchTree() {
        this.root = null;
        this.size = 0;
    }

    /**
     * 返回二叉树的节点个数
     * @return
     */
    public int size() {
        return size;
    }

    /**
     * 判断二叉树是否为空
     * @return
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 向二分搜索树中添加新的元素e
     * @param e
     */
    public void add(E e) {
        root = add(root, e);
    }

    /**
     * 向以node为根的二分搜索树中插入元素e，递归算法
     * 返回插入新节点后二分搜索树的根
     * @param node  要插入的二叉树的根
     * @param e     插入的元素
     * @return      插入节点后的二叉树的根节点
     */
    private Node add(Node node, E e) {
        if (node == null) {
            size ++;
            return new Node(e);
        }
        if (e.compareTo(node.e) < 0) {
            node.left = add(node.left, e);
        } else if (e.compareTo(node.e) > 0) {
            node.right = add(node.right, e);
        }
        return node;
    }

    /**
     * 比较复杂的一种递归添加的方法
     * @param node
     * @param e
     */
    private void add1(Node node, E e) {
        if (e.equals(node.e)) {
            return;
        } else if (e.compareTo(node.e) < 0 && node.left == null) {
            node.left = new Node(e);
            size ++;
            return;
        } else if (e.compareTo(node.e) > 0 && node.right == null) {
            node.right = new Node(e);
            size ++;
            return;
        }

        if (e.compareTo(node.e) < 0) {
            add1(node.left, e);
        } else {
            add1(node.right, e);
        }
    }

    /**
     * 是否包含某个元素
     * @param e 某个元素
     * @return
     */
    public boolean contains(E e) {
        return contains(root, e);
    }

    /**
     * 在以node为根节点的二分搜索树中查看是否包含某个节点
     * @param node  根节点
     * @param e     某个节点
     * @return
     */
    private boolean contains(Node node, E e) {
        if (node == null) {
            return false;
        }

        if (node.e.compareTo(e) == 0) {
            return true;
        } else if (node.e.compareTo(e) < 0) {
            return contains(node.left, e);
        } else {
            return contains(node.right, e);
        }
    }

    /**
     * 前序遍历二分搜索树
     * 遍历的顺序是：根节点-->左子树-->右子树
     */
    public void preOrder() {
        preOrder(root);
    }

    private void preOrder(Node node) {
        if (node == null) {
            return;
        }
        System.out.println(node.e);
        preOrder(node.left);
        preOrder(node.right);
    }

    /**
     * 前序遍历二分搜索树的非递归写法（NR：not recursive）
     * 遍历的顺序是：根节点-->左子树-->右子树
     */
    public void preOrderNR() {
        if (root == null) {
            return;
        }
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node cur = stack.pop();
            System.out.println(cur.e);
            if (cur.right != null) {
                stack.push(cur.right);
            }
            if (cur.left != null) {
                stack.push(cur.left);
            }
        }
    }

    /**
     * 中序遍历二分搜索树
     * 遍历的顺序是：左子树-->根节点-->右子树
     */
    public void inOrder() {
        inOrder(root);
    }

    private void inOrder(Node node) {
        if (node == null) {
            return;
        }

        inOrder(node.left);
        System.out.println(node.e);
        inOrder(node.right);
    }

    /**
     * 后序遍历二分搜索树
     * 遍历的顺序是：左子树-->右子树-->根节点
     */
    public void postOrder() {
        postOrder(root);
    }

    private void postOrder(Node node) {
        if (node == null) {
            return;
        }
        postOrder(node.left);
        postOrder(node.right);
        System.out.println(node.e);
    }

    /**
     * 二分搜索树的层序遍历（也叫：广度优先遍历）
     */
    public void levelOrder() {
        if (root == null) {
            return;
        }
        Queue<Node> queue = new LoopQueue<>();
        queue.enqueue(root);
        while (!queue.isEmpty()) {
            Node cur = queue.dequeue();
            System.out.println(cur.e);
            if (cur.left != null) {
                queue.enqueue(cur.left);
            }
            if (cur.right != null) {
                queue.enqueue(cur.right);
            }
        }
    }

    /**
     * 使用非递归的方式，获取二分搜索树的最小节点
     * @return
     */
    public E getMinNodeValue() {
        if (size == 0) {
            throw new IllegalArgumentException("Binary Search Tree is Empty.");
        }
        Node cur = root;
        while (cur.left != null) {
            cur = cur.left;
        }
        return cur.e;
    }

    /**
     * 使用递归的方式获取二分搜索树的最小节点的值
     * @return
     */
    public E minimum() {
        if (size == 0) {
            throw new IllegalArgumentException("Binary Search Tree is Empty.");
        }
        return minimum(root).e;
    }

    /**
     * 使用递归的方式获取二分搜索树的最小节点
     * @param node
     * @return
     */
    private Node minimum(Node node) {
        if (node.left == null) {
            return node;
        }
        return minimum(node.left);
    }

    /**
     * 使用非递归的方式，获取二分搜索树的最大节点
     * @return
     */
    public E getMaxNodeValue() {
        if (size == 0) {
            throw new IllegalArgumentException("Binary Search Tree is Empty.");
        }
        Node cur = root;
        while (cur.right != null) {
            cur = cur.right;
        }
        return cur.e;
    }

    /**
     * 使用递归的方式获取二分搜索树的最小节点的值
     * @return
     */
    public E maximum() {
        if (size == 0) {
            throw new IllegalArgumentException("Binary Search Tree is Empty.");
        }
        return maximum(root).e;
    }

    /**
     * 使用递归的方式获取二分搜索树的最小节点
     * @param node
     * @return
     */
    private Node maximum(Node node) {
        if (node.right == null) {
            return node;
        }
        return maximum(node.right);
    }

    /**
     * 移除最小值对应的节点
     * @return
     */
    public E removeMin() {
        E ret = minimum();
        root = removeMin(root);
        return ret;
    }

    private Node removeMin(Node node) {
        if (node.left == null) {
            Node rightNode = node.right;
            node.right = null;
            size --;
            return rightNode;
        }
        node.left = removeMin(node.left);
        return node;
    }

    /**
     * 移除最小值对应的节点
     * @return
     */
    public E removeMax() {
        E ret = maximum();
        root = removeMax(root);
        return ret;
    }

    private Node removeMax(Node node) {
        if (node.right == null) {
            Node leftNode = node.left;
            node.left = null;
            size --;
            return leftNode;
        }
        node.right = removeMax(node.right);
        return node;
    }

    public void remove(E e) {
        root = remove(root, e);
    }

    private Node remove(Node node, E e) {
        if (node == null) {
            return null;
        }
        if (e.compareTo(node.e) < 0) {
            node.left = remove(node.left, e);
            return node;
        } else if (e.compareTo(node.e) > 0) {
            node.right = remove(node.right, e);
            return node;
        } else {
            // e.compareTo(node.e) == 0
            if (node.left == null) {
                // 待删除结点左子树为空的情况
                Node rightNode = node.right;
                node.right = null;
                size --;
                return rightNode;
            }

            if (node.right == null) {
                // 待删除结点右子树为空的情况
                Node leftNode = node.left;
                node.left = null;
                size --;
                return leftNode;
            }

            // 待删除结点左右子树都不为空的情况
            // 找到比待删除结点大的最小结点，即待删除结点右子树的最小结点
            // 用这个结点顶替待删除结点的位置
            Node successor = minimum(node.right);
            successor.right = removeMin(node.right);
            successor.left = node.left;

            node.left = node.right = null;
            return successor;
        }
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        generateToString(root, 0, res);
        return res.toString();
    }

    private void generateToString(Node node, int depth, StringBuilder res) {
        if (node == null) {
            res.append(generateDepthString(depth) + "null\n");
            return;
        }

        res.append(generateDepthString(depth) + node.e + "\n");
        generateToString(node.left, depth + 1, res);
        generateToString(node.right, depth + 1, res);
    }

    private String generateDepthString(int depth) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            res.append("--");
        }
        return res.toString();
    }
}
